import { reqUserAddress, reqDeleteAddress } from '../../../api/address'
// 获取应用实例
const app = getApp()
Page({
  // 页面的初始数据
  data: {
    addressList: [],
    selected: []
  },
  onLoad(options) {
    this.flag = options.flag
  },
  // 更新全局收货地址
  changeAddress(event) {
    if (this.flag !== '1') return
    const { id: addressId } = event.currentTarget.dataset
    const selectAddress = this.data.addressList.find((item) => item.id === addressId)
    if (selectAddress) {
      app.globalData.address = selectAddress
      wx.navigateBack()
    }
  },
  onTap() {
    this.data.selected.forEach((instance) => {
      instance.close()
    })
    this.setData({
      selected: []
    })
  },
  onOpen(event) {
    const { id } = event.currentTarget.dataset
    const instance = this.selectComponent(`#swipCell-${id}`)
    this.data.selected.push(instance)
  },
  deleteAddress(event) {
    const { id } = event.currentTarget.dataset
    wx.showModal({
      title: '提示',
      content: '确认要删除该收货地址吗?',
      confirmColor: '#f3514f',
      complete: (res) => {
        if (res.confirm) {
          reqDeleteAddress(id).then(() => {
            wx.showToast({
              title: '收货地址删除成功',
              icon: 'none'
            })
            this.getAddressList()
          })
        }
      }
    })
  },
  getAddressList() {
    reqUserAddress().then((res) => {
      this.setData({
        addressList: res.data
      })
    })
  },
  // 因为当用户点击编辑或者新增的时候 页面是没有销毁的 所以不能使用onLoad钩子函数
  onShow() {
    this.getAddressList()
  },
  // 去编辑页面
  toEdit(event) {
    const { id } = event.currentTarget.dataset
    wx.navigateTo({
      url: `/modules/settingModule/pages/address/add/index?id=${id}`
    })
  }
})
